package com.aoip.telemetry.telemetry.core.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * mybatis-plus 自动填充配置类
 *
 * @author chenbai
 * @version 1.0
 * @date 2021/7/8 16:10
 */
@Slf4j
@Component
public class ModelMetaObjectHandler implements MetaObjectHandler {

    private static final String CREATE_TIME_FIELD = "createTime";
    private static final String MODIFY_TIME_FIELD = "modifyTime";
    private static final String DEL_FLAG_FIELD = "delFlag";
    private static final String VERSION_FIELD = "version";

    @Override
    public void insertFill(MetaObject metaObject) {
//        this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
        // 起始版本 3.3.3(推荐)
        Object version;
        if (metaObject.hasGetter(CREATE_TIME_FIELD)) {
            version = this.getFieldValByName(CREATE_TIME_FIELD, metaObject);
            if (null == version) {
                this.setFieldValByName(CREATE_TIME_FIELD, LocalDateTime.now(), metaObject);
            }
        }
        if (metaObject.hasGetter(MODIFY_TIME_FIELD)) {
            version = this.getFieldValByName(MODIFY_TIME_FIELD, metaObject);
            if (null == version) {
                this.setFieldValByName(MODIFY_TIME_FIELD, LocalDateTime.now(), metaObject);
            }
        }
        if (metaObject.hasGetter(DEL_FLAG_FIELD)) {
            version = this.getFieldValByName(DEL_FLAG_FIELD, metaObject);
            if (null == version) {
                this.setFieldValByName(DEL_FLAG_FIELD, 0, metaObject);
            }
        }
        if (metaObject.hasGetter(VERSION_FIELD)) {
            version = this.getFieldValByName(VERSION_FIELD, metaObject);
            if (null == version) {
                this.setFieldValByName(VERSION_FIELD, 0L, metaObject);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
//        this.strictUpdateFill(metaObject, MODIFY_TIME_FIELD,  LocalDateTime::now, LocalDateTime.class);
        // 起始版本 3.3.3(推荐)
        this.setFieldValByName(MODIFY_TIME_FIELD, LocalDateTime.now(), metaObject);
    }

}
